import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, AbstractControl } from '@angular/forms';
import { QuestionBase } from './question-base';
@Component({
    selector: 'guide-df-question',
    templateUrl: 'dynamic-form-question.component.html',
    styles: [
            `input.ng-valid  {border-left: 5px solid #42A948; /* green */} 
            input.ng-invalid:not(form)  { border-left: 5px solid #a94442; /* red */}`
    ]
})
export class DynamicFormQuestionComponent implements OnInit {
    @Input() question: QuestionBase<any>;
    @Input() error: string;
    @Input() form: FormGroup;
    formControl: AbstractControl;

    ngOnInit() {
        for (const key in this.form.controls) {
            if (this.form.controls.hasOwnProperty(key)) {
                if (key === this.question.key) {
                    this.formControl = this.form.controls[key];
                }
            }
        }
    }

    get errorMessage() {
        if (this.formControl.errors) {
            for (const key in this.formControl.errors) {
                if (this.formControl.errors.hasOwnProperty(key)) {
                    return this.question.errorMessages[key];
                }
            }
        }
        return '';
    }

}
